Passed
Pull Request — master (#1066)
by
unknown
03:31
created

script.js ➔ use   F

Complexity

Conditions 23

Size

Total Lines 100
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 60
dl 0
loc 100
rs 0
c 0
b 0
f 0
cc 23

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like script.js ➔ use often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
var lfm_route = location.origin + location.pathname;
2
var show_list;
3
var sort_type = 'alphabetic';
4
var multi_selection_enabled = false;
5
var selected = [];
6
var items = [];
7
var key_auth_token = 'key_auth_token';
8
var route_check_authenticate = 'route_check_authenticate';
9
var no_authenticate_redirect_to = 'no_authenticate_redirect_to'
10
11
$.fn.fab = function (options) {
12
  var menu = this;
13
  menu.addClass('fab-wrapper');
14
15
  var toggler = $('<a>')
16
    .addClass('fab-button fab-toggle')
17
    .append($('<i>').addClass('fas fa-plus'))
18
    .click(function () {
19
      menu.toggleClass('fab-expand');
20
    });
21
22
  menu.append(toggler);
23
24
  options.buttons.forEach(function (button) {
25
    toggler.before(
26
      $('<a>').addClass('fab-button fab-action')
27
        .attr('data-label', button.label)
28
        .attr('id', button.attrs.id)
29
        .append($('<i>').addClass(button.icon))
30
        .click(function () {
31
          menu.removeClass('fab-expand');
32
        })
33
    );
34
  });
35
};
36
37
$(document).ready(function () {
38
  $('#fab').fab({
39
    buttons: [
40
      {
41
        icon: 'fas fa-upload',
42
        label: lang['nav-upload'],
43
        attrs: {id: 'upload'}
44
      },
45
      {
46
        icon: 'fas fa-folder',
47
        label: lang['nav-new'],
48
        attrs: {id: 'add-folder'}
49
      }
50
    ]
51
  });
52
53
  actions.reverse().forEach(function (action) {
54
    $('#nav-buttons > ul').prepend(
55
      $('<li>').addClass('nav-item').append(
56
        $('<a>').addClass('nav-link d-none')
57
          .attr('data-action', action.name)
58
          .attr('data-multiple', action.multiple)
59
          .append($('<i>').addClass('fas fa-fw fa-' + action.icon))
60
          .append($('<span>').text(action.label))
61
      )
62
    );
63
  });
64
65
  sortings.forEach(function (sort) {
66
    $('#nav-buttons .dropdown-menu').append(
67
      $('<a>').addClass('dropdown-item').attr('data-sortby', sort.by)
68
        .append($('<i>').addClass('fas fa-fw fa-' + sort.icon))
69
        .append($('<span>').text(sort.label))
70
        .click(function() {
71
          sort_type = sort.by;
72
          loadItems();
73
        })
74
    );
75
  });
76
77
  loadFolders();
78
  performLfmRequest('errors')
79
    .done(function (response) {
80
      JSON.parse(response).forEach(function (message) {
81
        $('#alerts').append(
82
          $('<div>').addClass('alert alert-warning')
83
            .append($('<i>').addClass('fas fa-exclamation-circle'))
84
            .append(' ' + message)
85
        );
86
      });
87
    });
88
89
  $(window).on('dragenter', function(){
90
    $('#uploadModal').modal('show');
91
  });
92
93
  if (usingWysiwygEditor()) {
94
    $('#multi_selection_toggle').hide();
95
  }
96
});
97
98
// ======================
99
// ==  Navbar actions  ==
100
// ======================
101
102
$('#multi_selection_toggle').click(function () {
103
  multi_selection_enabled = !multi_selection_enabled;
104
105
  $('#multi_selection_toggle i')
106
    .toggleClass('fa-times', multi_selection_enabled)
107
    .toggleClass('fa-check-double', !multi_selection_enabled);
108
109
  if (!multi_selection_enabled) {
110
    clearSelected();
111
  }
112
});
113
114
$('#to-previous').click(function () {
115
  var previous_dir = getPreviousDir();
116
  if (previous_dir == '') return;
117
  goTo(previous_dir);
118
});
119
120
function toggleMobileTree(should_display) {
121
  if (should_display === undefined) {
122
    should_display = !$('#tree').hasClass('in');
123
  }
124
  $('#tree').toggleClass('in', should_display);
125
}
126
127
$('#show_tree').click(function (e) {
128
  toggleMobileTree();
129
});
130
131
$('#main').click(function (e) {
132
  if ($('#tree').hasClass('in')) {
133
    toggleMobileTree(false);
134
  }
135
});
136
137
$(document).on('click', '#add-folder', function () {
138
  dialog(lang['message-name'], '', createFolder);
139
});
140
141
$(document).on('click', '#upload', function () {
142
  $('#uploadModal').modal('show');
143
});
144
145
$(document).on('click', '[data-display]', function() {
146
  show_list = $(this).data('display');
147
  loadItems();
148
});
149
150
$(document).on('click', '[data-action]', function() {
151
  window[$(this).data('action')]($(this).data('multiple') ? getSelectedItems() : getOneSelectedElement());
152
});
153
154
// ==========================
155
// ==  Multiple Selection  ==
156
// ==========================
157
158
function toggleSelected (e) {
159
  if (!multi_selection_enabled) {
160
    selected = [];
161
  }
162
163
  var sequence = $(e.target).closest('a').data('id');
164
  var element_index = selected.indexOf(sequence);
165
  if (element_index === -1) {
166
    selected.push(sequence);
167
  } else {
168
    selected.splice(element_index, 1);
169
  }
170
171
  updateSelectedStyle();
172
}
173
174
function clearSelected () {
175
  selected = [];
176
177
  multi_selection_enabled = false;
178
179
  updateSelectedStyle();
180
}
181
182
function updateSelectedStyle() {
183
  items.forEach(function (item, index) {
184
    $('[data-id=' + index + ']')
185
      .find('.square')
186
      .toggleClass('selected', selected.indexOf(index) > -1);
187
  });
188
  toggleActions();
189
}
190
191
function getOneSelectedElement(orderOfItem) {
192
  var index = orderOfItem !== undefined ? orderOfItem : selected[0];
193
  return items[index];
194
}
195
196
function getSelectedItems() {
197
  return selected.reduce(function (arr_objects, id) {
198
    arr_objects.push(getOneSelectedElement(id));
199
    return arr_objects
200
  }, []);
201
}
202
203
function toggleActions() {
204
  var one_selected = selected.length === 1;
205
  var many_selected = selected.length >= 1;
206
  var only_image = getSelectedItems()
207
    .filter(function (item) { return !item.is_image; })
208
    .length === 0;
209
  var only_file = getSelectedItems()
210
    .filter(function (item) { return !item.is_file; })
211
    .length === 0;
212
213
  $('[data-action=use]').toggleClass('d-none', !(many_selected && only_file));
214
  $('[data-action=rename]').toggleClass('d-none', !one_selected);
215
  $('[data-action=preview]').toggleClass('d-none', !(many_selected && only_file));
216
  $('[data-action=move]').toggleClass('d-none', !many_selected);
217
  $('[data-action=download]').toggleClass('d-none', !(many_selected && only_file));
218
  $('[data-action=resize]').toggleClass('d-none', !(one_selected && only_image));
219
  $('[data-action=crop]').toggleClass('d-none', !(one_selected && only_image));
220
  $('[data-action=trash]').toggleClass('d-none', !many_selected);
221
  $('[data-action=open]').toggleClass('d-none', !one_selected || only_file);
222
  $('#multi_selection_toggle').toggleClass('d-none', usingWysiwygEditor() || !many_selected);
223
  $('#actions').toggleClass('d-none', selected.length === 0);
224
  $('#fab').toggleClass('d-none', selected.length !== 0);
225
}
226
227
// ======================
228
// ==  Folder actions  ==
229
// ======================
230
231
$(document).on('click', '#tree a', function (e) {
232
  goTo($(e.target).closest('a').data('path'));
233
  toggleMobileTree(false);
234
});
235
236
function goTo(new_dir) {
237
  $('#working_dir').val(new_dir);
238
  loadItems();
239
}
240
241
function getPreviousDir() {
242
  var working_dir = $('#working_dir').val();
243
  return working_dir.substring(0, working_dir.lastIndexOf('/'));
244
}
245
246
function setOpenFolders() {
247
  $('#tree [data-path]').each(function (index, folder) {
248
    // close folders that are not parent
249
    var should_open = ($('#working_dir').val() + '/').startsWith($(folder).data('path') + '/');
250
    $(folder).children('i')
251
      .toggleClass('fa-folder-open', should_open)
252
      .toggleClass('fa-folder', !should_open);
253
  });
254
255
  $('#tree .nav-item').removeClass('active');
256
  $('#tree [data-path="' + $('#working_dir').val() + '"]').parent('.nav-item').addClass('active');
257
}
258
259
// ====================
260
// ==  Ajax actions  ==
261
// ====================
262
263
function performLfmRequest(url, parameter, type) {
264
265
  var data = defaultParameters();
266
  
267
  if (parameter != null) {
268
    $.each(parameter, function (key, value) {
269
      data[key] = value;
270
    });
271
  }
272
273
  const request = (token) => {
274
    return $.ajax({
275
        type: "GET",
276
        beforeSend: async function(request) {
277
            if (token !== null) {
278
                request.setRequestHeader("Authorization", "Bearer " + token);
279
            }
280
        },
281
        dataType: type || "text",
282
        url: lfm_route + "/" + url,
283
        data: data,
284
        cache: false
285
    });
286
  }
287
288
  // If authenticate with token, this step check authenticate
289
  var keyAuthToken = localStorage.getItem(key_auth_token);
290
  if (keyAuthToken != null && keyAuthToken != "") {
291
    var token = localStorage.getItem(keyAuthToken);
292
    var urlApiAuthenticate = localStorage.getItem(route_check_authenticate);
293
    return $.ajax({
294
        method: "GET",
295
        url: urlApiAuthenticate,
296
        headers: {
297
            Authorization: "Bearer " + token
298
        },
299
        cache: false
300
    }).then(response => {
301
      return request(token).catch(({statusText}) => {
302
        let redirect_to = localStorage.getItem(no_authenticate_redirect_to);
303
        return displayErrorResponseFromApi(statusText, redirect_to);
304
      });
305
    }).catch(({responseJSON: { data, message}, status}) => {
306
      if(status == 401){
307
        let { authorization, redirect_to } = data; 
308
        return displayErrorResponseFromApi(message, redirect_to)
309
      } else {
310
        let redirect_to = localStorage.getItem(no_authenticate_redirect_to); 
311
        displayErrorResponseFromApi(message, redirect_to);
312
      }
313
      return Promise.resolve()
314
    });
315
  } else {
316
    var token = getUrlParam("token");
317
    return request(token).fail(function(jqXHR, textStatus, errorThrown) {
318
        displayErrorResponse(jqXHR);
319
    });
320
  }
321
}
322
323
function displayErrorResponseFromApi(message, urlRedirectBack){
324
  notifyAuthenticate(`
325
    <div style="max-height:50vh;">
326
      <p>${message}</p>
327
    </div>
328
  `, () => {
329
    window.location.replace(urlRedirectBack)
330
  });
331
}
332
333
function displayErrorResponse(jqXHR) {
334
  notify('<div style="max-height:50vh;overflow: scroll;">' + jqXHR.responseText + '</div>');
335
}
336
337
var refreshFoldersAndItems = function (data) {
338
  loadFolders();
339
  if (data != 'OK') {
340
    data = Array.isArray(data) ? data.join('<br/>') : data;
341
    notify(data);
342
  }
343
};
344
345
var hideNavAndShowEditor = function (data) {
346
  $('#nav-buttons > ul').addClass('d-none');
347
  $('#content').html(data);
348
  $('#pagination').removeClass('preserve_actions_space')
349
  clearSelected();
350
}
351
352
function loadFolders() {
353
  performLfmRequest('folders', {}, 'html')
354
    .done(function (data) {
355
      $('#tree').html(data);
356
      loadItems();
357
    });
358
}
359
360
function generatePaginationHTML(el, args) {
361
  var template = '<li class="page-item"><\/li>';
362
  var linkTemplate = '<a class="page-link"><\/a>';
363
  var currentPage = args.currentPage;
364
  var totalPage = args.totalPage;
365
  var rangeStart = args.rangeStart;
366
  var rangeEnd = args.rangeEnd;
367
  var i;
368
369
  // Disable page range, display all the pages
370
  if (args.pageRange === null) {
371
    for (i = 1; i <= totalPage; i++) {
372
      var button = $(template)
373
        .attr('data-num', i)
374
        .append($(linkTemplate).html(i));
375
      if (i == currentPage) {
376
        button.addClass('active');
377
      }
378
      el.append(button);
379
    }
380
381
    return;
382
  }
383
384
  if (rangeStart <= 3) {
385
    for (i = 1; i < rangeStart; i++) {
386
      var button = $(template)
387
        .attr('data-num', i)
388
        .append($(linkTemplate).html(i));
389
      if (i == currentPage) {
390
        button.addClass('active');
391
      }
392
      el.append(button);
393
    }
394
  } else {
395
    var button = $(template)
396
      .attr('data-num', 1)
397
      .append($(linkTemplate).html(1));
398
    el.append(button);
399
400
    var button = $(template)
401
      .addClass('disabled')
402
      .append($(linkTemplate).html('...'));
403
    el.append(button);
404
  }
405
406
  for (i = rangeStart; i <= rangeEnd; i++) {
407
    var button = $(template)
408
      .attr('data-num', i)
409
      .append($(linkTemplate).html(i));
410
    if (i == currentPage) {
411
      button.addClass('active');
412
    }
413
    el.append(button);
414
  }
415
416
  if (rangeEnd >= totalPage - 2) {
417
    for (i = rangeEnd + 1; i <= totalPage; i++) {
418
      var button = $(template)
419
        .attr('data-num', i)
420
        .append($(linkTemplate).html(i));
421
      el.append(button);
422
    }
423
  } else {
424
    var button = $(template)
425
      .addClass('disabled')
426
      .append($(linkTemplate).html('...'));
427
    el.append(button);
428
429
    var button = $(template)
430
      .attr('data-num', totalPage)
431
      .append($(linkTemplate).html(totalPage));
432
    el.append(button);
433
  }
434
}
435
436
function createPagination(paginationSetting) {
437
  var el = $('<ul class="pagination" role="navigation"></ul>');
438
439
  var currentPage = paginationSetting.current_page;
440
  var pageRange = 5;
441
  var totalPage = Math.ceil(paginationSetting.total / paginationSetting.per_page);
442
443
  var rangeStart = currentPage - pageRange;
444
  var rangeEnd = currentPage + pageRange;
445
446
  if (rangeEnd > totalPage) {
447
    rangeEnd = totalPage;
448
    rangeStart = totalPage - pageRange * 2;
449
    rangeStart = rangeStart < 1 ? 1 : rangeStart;
450
  }
451
452
  if (rangeStart <= 1) {
453
    rangeStart = 1;
454
    rangeEnd = Math.min(pageRange * 2 + 1, totalPage);
455
  }
456
457
  generatePaginationHTML(el, {
458
    totalPage: totalPage,
459
    currentPage: currentPage,
460
    pageRange: pageRange,
461
    rangeStart: rangeStart,
462
    rangeEnd: rangeEnd
463
  });
464
465
  $('#pagination').append(el);
466
}
467
468
function loadItems(page) {
469
  loading(true);
470
  performLfmRequest('jsonitems', {show_list: show_list, sort_type: sort_type, page: page || 1}, 'html')
471
    .done(function (data) {
472
      selected = [];
473
      var response = JSON.parse(data);
474
      var working_dir = response.working_dir;
475
      items = response.items;
476
      var hasItems = items.length !== 0;
477
      var hasPaginator = !!response.paginator;
478
      $('#empty').toggleClass('d-none', hasItems);
479
      $('#content').html('').removeAttr('class');
480
      $('#pagination').html('').removeAttr('class');
481
482
      if (hasItems) {
483
        $('#content').addClass(response.display);
484
        $('#pagination').addClass('preserve_actions_space');
485
486
        items.forEach(function (item, index) {
487
          var template = $('#item-template').clone()
488
            .removeAttr('id class')
489
            .attr('data-id', index)
490
            .click(toggleSelected)
491
            .dblclick(function (e) {
492
              if (item.is_file) {
493
                use(getSelectedItems());
494
              } else {
495
                goTo(item.url);
496
              }
497
            });
498
499
          if (item.thumb_url) {
500
            var image = $('<div>').css('background-image', 'url("' + item.thumb_url + '?timestamp=' + item.time + '")');
501
          } else {
502
            var icon = $('<div>').addClass('ico');
503
            var image = $('<div>').addClass('mime-icon ico-' + item.icon).append(icon);
504
          }
505
506
          template.find('.square').append(image);
507
          template.find('.item_name').text(item.name);
508
          template.find('time').text((new Date(item.time * 1000)).toLocaleString());
509
510
          $('#content').append(template);
511
        });
512
      }
513
514
      if (hasPaginator) {
515
        createPagination(response.paginator);
516
517
        $('#pagination a').on('click', function(event) {
518
          event.preventDefault();
519
520
          loadItems($(this).closest('li')[0].getAttribute('data-num'));
521
522
          return false;
523
        });
524
      }
525
526
      $('#nav-buttons > ul').removeClass('d-none');
527
528
      $('#working_dir').val(working_dir);
529
      console.log('Current working_dir : ' + working_dir);
530
      var breadcrumbs = [];
531
      var validSegments = working_dir.split('/').filter(function (e) { return e; });
532
      validSegments.forEach(function (segment, index) {
533
        if (index === 0) {
534
          // set root folder name as the first breadcrumb
535
          breadcrumbs.push($("[data-path='/" + segment + "']").text());
536
        } else {
537
          breadcrumbs.push(segment);
538
        }
539
      });
540
541
      $('#current_folder').text(breadcrumbs[breadcrumbs.length - 1]);
542
      $('#breadcrumbs > ol').html('');
543
      breadcrumbs.forEach(function (breadcrumb, index) {
544
        var li = $('<li>').addClass('breadcrumb-item').text(breadcrumb);
545
546
        if (index === breadcrumbs.length - 1) {
547
          li.addClass('active').attr('aria-current', 'page');
548
        } else {
549
          li.click(function () {
550
            // go to corresponding path
551
            goTo('/' + validSegments.slice(0, 1 + index).join('/'));
552
          });
553
        }
554
555
        $('#breadcrumbs > ol').append(li);
556
      });
557
558
      var atRootFolder = getPreviousDir() == '';
559
      $('#to-previous').toggleClass('d-none invisible-lg', atRootFolder);
560
      $('#show_tree').toggleClass('d-none', !atRootFolder).toggleClass('d-block', atRootFolder);
561
      setOpenFolders();
562
      loading(false);
563
      toggleActions();
564
    });
565
}
566
567
function loading(show_loading) {
568
  $('#loading').toggleClass('d-none', !show_loading);
569
}
570
571
function createFolder(folder_name) {
572
  performLfmRequest('newfolder', {name: folder_name})
573
    .done(refreshFoldersAndItems);
574
}
575
576
// ==================================
577
// ==         File Actions         ==
578
// ==================================
579
580
function rename(item) {
581
  dialog(lang['message-rename'], item.name, function (new_name) {
582
    performLfmRequest('rename', {
583
      file: item.name,
584
      new_name: new_name
585
    }).done(refreshFoldersAndItems);
586
  });
587
}
588
589
function trash(items) {
590
  notify(lang['message-delete'], function () {
591
    performLfmRequest('delete', {
592
      items: items.map(function (item) { return item.name; })
593
    }).done(refreshFoldersAndItems)
594
  });
595
}
596
597
function crop(item) {
598
  performLfmRequest('crop', {img: item.name})
599
    .done(hideNavAndShowEditor);
600
}
601
602
function resize(item) {
603
  performLfmRequest('resize', {img: item.name})
604
    .done(hideNavAndShowEditor);
605
}
606
607
function download(items) {
608
  items.forEach(function (item, index) {
609
    var data = defaultParameters();
610
611
    data['file'] = item.name;
612
613
    var token = getUrlParam('token');
614
    if (token) {
615
      data['token'] = token;
616
    }
617
618
    setTimeout(function () {
619
      location.href = lfm_route + '/download?' + $.param(data);
620
    }, index * 100);
621
  });
622
}
623
624
function open(item) {
625
  goTo(item.url);
626
}
627
628
function preview(items) {
629
  var carousel = $('#carouselTemplate').clone().attr('id', 'previewCarousel').removeClass('d-none');
630
  var imageTemplate = carousel.find('.carousel-item').clone().removeClass('active');
631
  var indicatorTemplate = carousel.find('.carousel-indicators > li').clone().removeClass('active');
632
  carousel.children('.carousel-inner').html('');
633
  carousel.children('.carousel-indicators').html('');
634
  carousel.children('.carousel-indicators,.carousel-control-prev,.carousel-control-next').toggle(items.length > 1);
635
636
  items.forEach(function (item, index) {
637
    var carouselItem = imageTemplate.clone()
638
      .addClass(index === 0 ? 'active' : '');
639
640
    if (item.thumb_url) {
641
      carouselItem.find('.carousel-image').css('background-image', 'url(\'' + item.url + '?timestamp=' + item.time + '\')');
642
    } else {
643
      carouselItem.find('.carousel-image').css('width', '50vh').append($('<div>').addClass('mime-icon ico-' + item.icon));
644
    }
645
646
    carouselItem.find('.carousel-label').attr('target', '_blank').attr('href', item.url)
647
      .append(item.name)
648
      .append($('<i class="fas fa-external-link-alt ml-2"></i>'));
649
650
    carousel.children('.carousel-inner').append(carouselItem);
651
652
    var carouselIndicator = indicatorTemplate.clone()
653
      .addClass(index === 0 ? 'active' : '')
654
      .attr('data-slide-to', index);
655
    carousel.children('.carousel-indicators').append(carouselIndicator);
656
  });
657
658
659
  // carousel swipe control
660
  var touchStartX = null;
661
662
  carousel.on('touchstart', function (event) {
663
    var e = event.originalEvent;
664
    if (e.touches.length == 1) {
665
      var touch = e.touches[0];
666
      touchStartX = touch.pageX;
667
    }
668
  }).on('touchmove', function (event) {
669
    var e = event.originalEvent;
670
    if (touchStartX != null) {
671
      var touchCurrentX = e.changedTouches[0].pageX;
672
      if ((touchCurrentX - touchStartX) > 60) {
673
        touchStartX = null;
674
        carousel.carousel('prev');
675
      } else if ((touchStartX - touchCurrentX) > 60) {
676
        touchStartX = null;
677
        carousel.carousel('next');
678
      }
679
    }
680
  }).on('touchend', function () {
681
    touchStartX = null;
682
  });
683
  // end carousel swipe control
684
685
  notify(carousel);
686
}
687
688
function move(items) {
689
  performLfmRequest('move', { items: items.map(function (item) { return item.name; }) })
690
    .done(refreshFoldersAndItems);
691
}
692
693
function getUrlParam(paramName) {
694
  var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i');
695
  var match = window.location.search.match(reParam);
696
  return ( match && match.length > 1 ) ? match[1] : null;
697
}
698
699
function use(items) {
700
  function useTinymce3(url) {
701
    if (!usingTinymce3()) { return; }
702
703
    var win = tinyMCEPopup.getWindowArg("window");
704
    win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;
705
    if (typeof(win.ImageDialog) != "undefined") {
706
      // Update image dimensions
707
      if (win.ImageDialog.getImageData) {
708
        win.ImageDialog.getImageData();
709
      }
710
711
      // Preview if necessary
712
      if (win.ImageDialog.showPreviewImage) {
713
        win.ImageDialog.showPreviewImage(url);
714
      }
715
    }
716
    tinyMCEPopup.close();
717
  }
718
719
  function useTinymce4AndColorbox(url) {
720
    if (!usingTinymce4AndColorbox()) { return; }
721
722
    parent.document.getElementById(getUrlParam('field_name')).value = url;
723
724
    if(typeof parent.tinyMCE !== "undefined") {
725
      parent.tinyMCE.activeEditor.windowManager.close();
726
    }
727
    if(typeof parent.$.fn.colorbox !== "undefined") {
728
      parent.$.fn.colorbox.close();
729
    }
730
  }
731
732
  function useTinymce5(url){
733
    if (!usingTinymce5()) { return; }
734
735
    parent.postMessage({
736
      mceAction: 'insert',
737
      content: url
738
    });
739
740
    parent.postMessage({ mceAction: 'close' });
741
  }
742
743
  function useCkeditor3(url) {
744
    if (!usingCkeditor3()) { return; }
745
746
    if (window.opener) {
747
      // Popup
748
      window.opener.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
749
    } else {
750
      // Modal (in iframe)
751
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
752
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorCleanUpFuncNum'));
753
    }
754
  }
755
756
  function useFckeditor2(url) {
757
    if (!usingFckeditor2()) { return; }
758
759
    var p = url;
760
    var w = data['Properties']['Width'];
761
    var h = data['Properties']['Height'];
762
    window.opener.SetUrl(p,w,h);
763
  }
764
765
  var url = items[0].url;
766
  var callback = getUrlParam('callback');
767
  var useFileSucceeded = true;
768
769
  if (usingWysiwygEditor()) {
770
    useTinymce3(url);
771
772
    useTinymce4AndColorbox(url);
773
774
    useTinymce5(url);
775
776
    useCkeditor3(url);
777
778
    useFckeditor2(url);
779
  } else if (callback && window[callback]) {
780
    window[callback](getSelectedItems());
781
  } else if (callback && parent[callback]) {
782
    parent[callback](getSelectedItems());
783
  } else if (window.opener) { // standalone button or other situations
784
    window.opener.SetUrl(getSelectedItems());
785
  } else {
786
    useFileSucceeded = false;
787
  }
788
789
  if (useFileSucceeded) {
790
    if (window.opener) {
791
      window.close();
792
    }
793
  } else {
794
    console.log('window.opener not found');
795
    // No editor found, open/download file using browser's default method
796
    window.open(url);
797
  }
798
}
799
//end useFile
800
801
// ==================================
802
// ==     WYSIWYG Editors Check    ==
803
// ==================================
804
805
function usingTinymce3() {
806
  return !!window.tinyMCEPopup;
807
}
808
809
function usingTinymce4AndColorbox() {
810
  return !!getUrlParam('field_name');
811
}
812
813
function usingTinymce5(){
814
    return !!getUrlParam('editor');
815
}
816
817
function usingCkeditor3() {
818
  return !!getUrlParam('CKEditor') || !!getUrlParam('CKEditorCleanUpFuncNum');
819
}
820
821
function usingFckeditor2() {
822
  return window.opener && typeof data != 'undefined' && data['Properties']['Width'] != '';
823
}
824
825
function usingWysiwygEditor() {
826
  return usingTinymce3() || usingTinymce4AndColorbox() || usingTinymce5() || usingCkeditor3() || usingFckeditor2();
827
}
828
829
// ==================================
830
// ==            Others            ==
831
// ==================================
832
833
function defaultParameters() {
834
  return {
835
    working_dir: $('#working_dir').val(),
836
    type: $('#type').val()
837
  };
838
}
839
840
function notImp() {
841
  notify('Not yet implemented!');
842
}
843
844
function notifyAuthenticate(body, callback = null){
845
  $("#notify")
846
      .find(".btn-secondary")
847
      .unbind()
848
      .click(callback);
849
  $('#notify').modal('show').find('.modal-body').html(body)
850
  $('#notify').find('.btn-primary').hide();
851
}
852
853
function notify(body, callback) {
854
  $('#notify').find('.btn-primary').toggle(callback !== undefined);
855
  $('#notify').find('.btn-primary').unbind().click(callback);
856
  $('#notify').modal('show').find('.modal-body').html(body);
857
}
858
859
function dialog(title, value, callback) {
860
  $('#dialog').find('input').val(value);
861
  $('#dialog').on('shown.bs.modal', function () {
862
    $('#dialog').find('input').focus();
863
  });
864
  $('#dialog').find('.btn-primary').unbind().click(function (e) {
865
    callback($('#dialog').find('input').val());
866
  });
867
  $('#dialog').modal('show').find('.modal-title').text(title);
868
}
869